package com.sensePlusVR.receiver;

import java.util.HashMap;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;

import com.sensePlusVR.activity.listener.NetworkEvent;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.NetworkUtils;

public class NetworkReceiver extends BroadcastReceiver {
	private static final String TAG = NetworkReceiver.class.getSimpleName();
    private static HashMap<String, NetworkEvent> networkEvents = new HashMap<String,NetworkEvent>();
    
    static Object nLock = new Object();
    
	/**
	 * 设置监听网络变化回调
	 * @param callback
	 * @param param
	 */
	public static void setNetworkChangeNotify(NetworkEvent callback,String key){
		synchronized (nLock) {
			if(callback==null){
				networkEvents.remove(key);
			}else{
				networkEvents.put(key,callback);
			}
		}
	}
	
	
	/**
	 * 网络状态改变通知
	 */
	private static void onNetWorkChangeNotify(int netwrokState){
		synchronized (nLock) {
			for(String key:networkEvents.keySet()){
				NetworkEvent notify = networkEvents.get(key);
				if(notify!=null){
					notify.onNetChange(netwrokState);
				}
			}
		}
	}

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            //检查网络状态的类型
            int networkState = NetworkUtils.getNetConnectState(context);
            MyLog.d(TAG, "onReceive networkState : " + networkState);
            //接口回传网络状态的类型
            onNetWorkChangeNotify(networkState);
        }
    }
    
}
